//
//  LBMHomeTableViewController.swift
//  微博
//
//  Created by 刘保满 on 16/5/19.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HomeCellId = "HomeCellId"


class LBMHomeTableViewController: LBMBasicTableViewController {
    
    //自定义下拉刷新控件
    let refreshView = LBMRefreshControl()
    
    
    //tableView对应的视图模型
    lazy var statusListViewModel: LBMStatusListViewModel = LBMStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavBar()
        //如果没有登录,则会显示访客视图,不会显示tableview,所以注册会崩
        if !userLogin {
            
            visitorLoginView.updateUI("关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            
            return
        }
        //设置tablView
        prepareForTableView()
        
        //加载数据
        loadData()
        
        
    }
    
    private func prepareForTableView() {
        
        //注册
        tableView.registerClass(LBMStatusCell.self, forCellReuseIdentifier: HomeCellId)
        
        //设置预估行高
        tableView.estimatedRowHeight = 300
        
        //动态特性时用到
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //设置分隔线
        tableView.separatorStyle = .None
        
        //MARK: 使用自定义的下拉刷新
        
        //添加到tableView上
        self.tableView.addSubview(refreshView)
        
        //添加到导航条上
        self.navigationController?.navigationBar.addSubview(tipLabel)
        //移动到最底层
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        //添加响应事件
        refreshView.addTarget(self, action: #selector(LBMHomeTableViewController.loadData), forControlEvents: .ValueChanged)
        
        //        //设置下拉刷新
        //        refreshControl = UIRefreshControl()
        //        //添加响应事件
        //        refreshControl?.addTarget(self, action: #selector(LBMHomeTableViewController.loadData), forControlEvents: .ValueChanged)
        
        //设置tableviewFooterView
        tableView.tableFooterView = pullupView
        
    }
    
    
    private func setNavBar() {
        
        //直接使用UIBarButtonItem的分类创建
        let popItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(LBMHomeTableViewController.push))
        
        navigationItem.rightBarButtonItem = popItem
        
    }
    
    //点击右侧按钮跳转控制器
    @objc private func push() {
        
        let detail = LBMDetailViewController()
        
        detail.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(detail, animated: true)
        
        
    }
    
    //小菊花控件
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        
        return indicatorView
        
    }()
    
    
    //MARK: 给下拉刷新时加一个显示刷新出多少条数据的label
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", font: 15, textColor: UIColor.whiteColor())
        
        //刚开始是不让它显示的
        l.frame = CGRect(x: 0, y: -64, width: ScreenWidth, height: 40)
        
        l.backgroundColor = UIColor.greenColor()
        
        return l
    }()
    
    
    
}

//新建分类用来封装加载数据的方法
extension LBMHomeTableViewController {
    @objc private func loadData() {
        
        statusListViewModel.loadHomePage(pullupView.isAnimating()) { (isSuccess, count) in
            
            //停止下拉刷新的小菊花
            self.refreshView.endRefreshing()
            
            if !isSuccess {
                //失败
                SVProgressHUD.showErrorWithStatus(AppErroTip)
                return
            }
            //成功
            //判断是否是静默加载
            if self.pullupView.isAnimating() {
                //静默加载更多数据
                //停止上拉加载更多的小菊花转动
                self.pullupView.stopAnimating()
                
            } else {
                //不是静默加载,是下拉刷新
                //提示用户刷新了多少条数据
                self.startAnimation(count)
            }
            
            //刷新
            self.tableView.reloadData()
            
        }
        
    }
    
    //提示用户刷新了多少条数据
    private func startAnimation(count: Int) {
        //根据传递的数量来判断tiplabel上显示的内容
        let tipText = (count == 0) ? "没有新数据" : "有\(count)条新数据"
        tipLabel.text = tipText
        
        //用动画修改frame
        UIView.animateWithDuration(0.6, animations: {
            
            self.tipLabel.frame = CGRect(x: 0, y: 44, width: ScreenWidth, height: 40)
            
        }) { (_) in
            //执行完之后
            //再让它的frame回到原来
            UIView.animateWithDuration(0.3, delay: 1, options: [], animations: {
                
                self.tipLabel.frame = CGRect(x: 0, y: -64, width: ScreenWidth, height: 40)
                
                }, completion: nil)
            
        }
    }
    
}


extension LBMHomeTableViewController {
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.statusListViewModel.statusViewModelArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //用这个方法需要注册
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeCellId, forIndexPath: indexPath) as! LBMStatusCell
        
        //如果正在加载最后一行cell,并且小菊花没有转动的时候,开始加载老数据
        if indexPath.row == statusListViewModel.statusViewModelArray.count - 1 && !pullupView.isAnimating() {
            
            print("开始静默加载数据")
            pullupView.startAnimating()
            
            loadData()
            
        }
        
        //设置数据
        cell.statusViewModel = statusListViewModel.statusViewModelArray[indexPath.row]
        
        return cell
        
        
    }
    
    
    
}















